package cn.apienvrypt.util;

import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;

/**
 * @author lfj
 */
public class RSAUtil {

	/**
	 * encryption algorithm RSA
	 */
	public static final String KEY_ALGORITHM = "RSA";

	/**
	 * RSA Maximum Encrypted Plaintext Size
	 */
	private static final int MAX_ENCRYPT_BLOCK = 117;

	/**
	 * RSA Maximum decrypted ciphertext size
	 */
	private static final int MAX_DECRYPT_BLOCK = 256;

	/**
	 * encryption
	 *
	 * @param data      data
	 * @param publicKey publicKey
	 * @return byte
	 * @throws Exception Exception
	 */
	public static byte[] encrypt(byte[] data, String publicKey)
		throws Exception {
		byte[] keyBytes = Base64Util.decode(publicKey);
		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		Key publicK = keyFactory.generatePublic(x509KeySpec);
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.ENCRYPT_MODE, publicK);
		int inputLen = data.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] cache;
		int i = 0;
		// Sectional Encryption of Data
		while(inputLen - offSet > 0) {
			if(inputLen - offSet > MAX_ENCRYPT_BLOCK) {
				cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
			} else {
				cache = cipher.doFinal(data, offSet, inputLen - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * MAX_ENCRYPT_BLOCK;
		}
		byte[] encryptedData = out.toByteArray();
		out.close();
		return encryptedData;
	}

	/**
	 * Decrypt
	 *
	 * @param text       text
	 * @param privateKey privateKey
	 * @return byte
	 * @throws Exception Exception
	 */
	public static byte[] decrypt(byte[] text, String privateKey)
		throws Exception {
		byte[] keyBytes = Base64Util.decode(privateKey);
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.DECRYPT_MODE, privateK);
		int inputLen = text.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] cache;
		int i = 0;
		// Sectional Encryption of Data
		while(inputLen - offSet > 0) {
			if(inputLen - offSet > MAX_DECRYPT_BLOCK) {
				cache = cipher.doFinal(text, offSet, MAX_DECRYPT_BLOCK);
			} else {
				cache = cipher.doFinal(text, offSet, inputLen - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * MAX_DECRYPT_BLOCK;
		}
		byte[] decryptedData = out.toByteArray();
		out.close();
		return decryptedData;
	}

	/**
	 * 签名
	 *
	 * @param data       待签名数据
	 * @param privateKey 私钥
	 * @return 签名
	 */
	public static String sign(String data, PrivateKey privateKey) throws Exception {
		byte[] keyBytes = privateKey.getEncoded();
		PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		PrivateKey key = keyFactory.generatePrivate(keySpec);
		Signature signature = Signature.getInstance("SHA1WithRSA");
		signature.initSign(key);
		signature.update(data.getBytes(StandardCharsets.UTF_8));
		return new String(Base64.encodeBase64(signature.sign()), StandardCharsets.UTF_8);
	}

	/**
	 * 验签
	 *
	 * @param srcData   原始字符串
	 * @param publicKey 公钥
	 * @param sign      签名
	 * @return 是否验签通过
	 */
	public static boolean verify(String srcData, PublicKey publicKey, String sign) throws Exception {
		byte[] keyBytes = publicKey.getEncoded();
		X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		PublicKey key = keyFactory.generatePublic(keySpec);
		Signature signature = Signature.getInstance("SHA1WithRSA");
		signature.initVerify(key);
		signature.update(srcData.getBytes(StandardCharsets.UTF_8));
		return signature.verify(Base64.decodeBase64(sign.getBytes(StandardCharsets.UTF_8)));
	}

	/**
	 * 获取私钥
	 *
	 * @param privateKey 私钥字符串
	 * @return PrivateKey
	 */
	public static PrivateKey getPrivateKey(String privateKey) throws Exception {
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		byte[] decodedKey = Base64.decodeBase64(privateKey.getBytes(StandardCharsets.UTF_8));
		PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
		return keyFactory.generatePrivate(keySpec);
	}

	/**
	 * 获取公钥
	 *
	 * @param publicKey 公钥字符串
	 * @return PublicKey
	 */
	public static PublicKey getPublicKey(String publicKey) throws Exception {
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		byte[] decodedKey = Base64.decodeBase64(publicKey.getBytes(StandardCharsets.UTF_8));
		X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
		return keyFactory.generatePublic(keySpec);
	}

	public static void main(String[] args) throws Exception {
		String publicKey = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJ2mgErOvpK9i24CIvqZmH5Y9QCcef0Y3wGDh9q1nZJoe7SnBne3gyNCOfh+yUQclPyFR2RWrbX6R02gB/RPX0UCAwEAAQ==";
		String privateKey = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAnaaASs6+kr2LbgIi+pmYflj1AJx5/RjfAYOH2rWdkmh7tKcGd7eDI0I5+H7JRByU/IVHZFattfpHTaAH9E9fRQIDAQABAkBEeberxpU8Q5w2UjNDSkfUSWtRsqXB63WhwLHXq58foha8z/rQnoUxvH4gfpHxJKcPiOJKx6X4BATXCt76zdoZAiEA4V7xVPl4ln4FB+mnyfel+Mj20yS0fF/jgbO646ZEvUcCIQCzE3EGVFfx8vqceXTugIKx9pVKXICRyD+hFEuAhh2VEwIhANolWFv0DjE9UglStcLdH54siB3gjYNGHaVSHzhznF3JAiB9gECT+QRxkqJEi3KBvBrccj4KkW2hvb+qOjj36AZPdQIgSEEMkGJ0Qg7q2BWmBVhaxdQ1rx/QhXhSIsfL7wZadc4=";
		String data = "dNameZdBWddGH+s8l7zmf2yBaYFki93335I56+an2A4=";
		// RSA签名
		long t1 = System.currentTimeMillis();
		String sign = sign(data, getPrivateKey(privateKey));
		System.out.println(sign);
		long t2 = System.currentTimeMillis();

		System.out.println(t2 - t1);
		// RSA验签
		long t3 = System.currentTimeMillis();
		boolean result = verify(data, getPublicKey(publicKey),
			sign);
		long t4 = System.currentTimeMillis();
		System.out.println(t4 - t3);
		System.out.print("验签结果:" + result);
	}
}
